import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/common/token'
import { loadMenus } from '@/common/auth'
import store from '@/store'


import Test from '../views/Test.vue'
import Login from '../views/login.vue'
import Home from '../views/home.vue'


//home的子组件
import Welcome from '../views/welcome.vue'

Vue.use(VueRouter);

const homeRoute = {
  path: "/home",
  name: "Home",
  component: Home,
  children: [//home组件的子路由，若某个子路由为"xxx/yyy"，则在程序中应当使用路径："/home/xxx/yyy"
    {
      path: "",//子路由不能以"/"开头，如果需要表示子路由的根路径直接表达为""，即默认路径
      name: "Welcome",
      component: Welcome
    }
  ]
};

const routes = [
  {
    path: '/test',
    name: 'Test',
    component: Test
  },
  {
    path: '/', redirect: "/login"
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  homeRoute

  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  console.log("全局路由守卫：", "to", to, "from", from);
  const token = getToken();
  if (to.path != '/login' && !token) {
    next('/login');
  } else {
    if (store.getters.menus.length == 0) {//页面刷新
      loadMenus().then(() => {
        next(to);
      });
    } else {
      next();
    }
    //next();
  }
});

/**
 * VueRouter实例的matcher属性表示路由配置，改变该属性起到替换路由的作用，这个属性官方api没有介绍
 */
export const resetRouter = () => { router.matcher = new VueRouter({ routes }).matcher };

export const loadRouter = (menus) => {
  homeRoute.children = [{
    path: "",//子路由不能以"/"开头，如果需要表示子路由的根路径直接表达为""，即默认路径
    name: "Welcome",
    component: Welcome
  }];
  buildRoutes(menus, homeRoute.children);
  resetRouter();
  console.log("routes=>", routes);
};

const buildRoutes = (menus, routes) => {
  routes = routes || [];

  menus.forEach((menu) => {
    if (menu.menuUrl) {
      const route = {
        path: menu.menuUrl,
        name: menu.menuUrl.split("/")[1] + "_" + menu.menuUrl.split("/")[2],
        component: () => import('@/views' + menu.menuUrl + '/index.vue')
      }
      routes.push(route);
      if (menu.subMenus && menu.subMenus instanceof Array) {
        route.children = [];
        buildRoutes(menu.subMenus, route.children);
      }
    } else {
      if (menu.subMenus && menu.subMenus instanceof Array) {

        buildRoutes(menu.subMenus, routes);
      }
    }

  });

  return routes;
};


export default router
